#ifndef COMPASS_H
#define COMPASS_H

// Compass.h
#include <QRegularExpression>
#include <QDebug>
#include <qsettings.h>
#include <QDir>
#include <QVector>
#include <QQueue>
#include <QRandomGenerator>

#include "device.h"

class Compass : public Device {
    Q_OBJECT

private:
    int baudRate;
    double pitch = 0.0;
    double roll = 0.0;
    double heading = 0.0;
    int samplerate;
    QString portName;
    QString location;
    QSettings settings; // 设置对象
    bool status = false; // 状态
    QQueue<QVector<uint8_t>> waiters;
    QQueue<QVector<uint8_t>> lists;
    quint64 lastTick;

    QTextStream out;
    QQueue<QVector<uint8_t>> dataBuffer; // 数据缓冲区
    int maxBufferSize = 10; // 缓冲区最大大小
    bool isProcessing = false; // 标记是否正在处理数据

    int total = 0; // 总计报文
    int error = 0; // 错误报文

public:
    explicit Compass(QObject *parent = nullptr)
        : Device(parent), settings("D:/qt/config.ini", QSettings::IniFormat) { // 初始化QSettings

        loadSettings(); // 加载设置

        Compass::configureSerialPort();

        // 尝试打开串口
        if (!Compass::openSerialPort()) {
            qWarning() << "Failed to open serial port.";
        }

        Compass::setCycle();

        saveDataToCsv();

        // 连接 readyRead 信号到槽函数
        connect(&serialPort, &QSerialPort::readyRead, this, &Compass::readData);

        lastTick = QDateTime::currentDateTime().toMSecsSinceEpoch();
    }

    ~Compass() override {
        disconnect(&serialPort, &QSerialPort::readyRead, this, &Compass::readData);
        closePort();
        closeFile();
    }

    void configureSerialPort() override {
        serialPort.setPortName(portName); // 使用从配置文件读取的端口名
        serialPort.setBaudRate(baudRate);
        serialPort.setDataBits(QSerialPort::Data8);
        serialPort.setParity(QSerialPort::NoParity);
        serialPort.setStopBits(QSerialPort::OneStop);
        serialPort.setFlowControl(QSerialPort::NoFlowControl);
    }

    bool openSerialPort() override {
        return serialPort.open(QIODevice::ReadWrite);
    }

    QString getDeviceInfo() const override {
        QString message;
        message += "端口号: " + portName + "\n";
        QString flag  = (status == true) ? "成功" : "失败";
        message += "连接:" + flag + "\n";
        message += "波特率: " + QString::number(baudRate) + "\n";
        message += "采样频率: " + QString::number(samplerate) + " Hz\n";
        message += "保存路径: " + location + "\n";
        qInfo() << message;
        return message;
    }

    void setCycle() override;

public slots:
    void sendDeviceInformation();
    void findErrorThresholdExceeded();
    void query();
    void processBuffer();
    void readData();

private:
    void sendOnce();
    void receiveOnce(const QVector<uint8_t>& rawData);
    void loadSettings();
    double parseAngle(const QVector<uint8_t> &rawData, int startIndex);
    void saveDataToCsv();

    // 处理不完整帧头的情况
    void handleInvalidHeader(const QVector<uint8_t>& rawData, QVector<uint8_t>& message);

    // 处理校验和
    bool checkChecksum(const QVector<uint8_t>& mess);

    // 解析数据并发送信号
    void parseAndEmit(const QVector<uint8_t>& rawData);

    // 处理数据长度小于有效长度的情况
    void handleDataLengthLess(const QVector<uint8_t>& message, int dataLength);

    // 处理数据长度大于等于有效长度的情况
    void handleDataLengthGreater(const QVector<uint8_t>& message);

signals:
    void compassReceived(double pitch, double roll, double heading);  // 用于通知更新数据
    void compassDeciveReceived(const QString& device);
    void errorThresholdExceeded(int errorCount);

public:
    void closeFile();
    void closePort();
};

#endif // COMPASS_H
